/* function getUserStockByName(username, stockname){
	var user = getUser(username);
	console.log("Getting stocks for user: " + username + ".")
	for(var k = 0; k < user.stocks.length; k++){
		if(stockname == user.stocks[k].name){
			return user.stocks[k];
		}
	}	
}

function updateUserStocks(username, stockName, units){
	var userStock = getUserStockByName(username, stockName);
	var stockPrice = getStock(stockName).price;
	var updatedUser = getUser(username);
	if(userStock == null){
		console.log("User has not bought this stock before!");
		var newStock = { name: stockName, units: units};
		updatedUser.balance = updatedUser.balance - (stockPrice * units);
		console.log("New balance is: " + updatedUser.balance);
		updatedUser.stocks.push(newStock);
	}
	else {
		userStock.units += units;
		updatedUser.balance = updatedUser.balance - (stockPrice * units);
		console.log("New balance is: " + updatedUser.balance);
	}
} */

	  //$(".buyStock").click(function(){
	//	alert("Buying");
		//var stockNameToBuy = $(this).attr("id");
		//now.buyStock("MSFT", 2);
	  //});	
	  
	  	//Countdown timer
		//javascript_countdown.init(3600, 'javascript_countdown_time');
	var javascript_countdown = function () {
		var time_left = 10; //number of seconds for countdown
		var output_element_id = 'javascript_countdown_time';
		var keep_counting = 1;
		var no_time_left_message = 'No time left for JavaScript countdown!';
	 
		function countdown() {
			if(time_left < 2) {
				keep_counting = 0;
			}
	 
			time_left = time_left - 1;
		}
	 
		function add_leading_zero(n) {
			if(n.toString().length < 2) {
				return '0' + n;
			} else {
				return n;
			}
		}
	 
		function format_output() {
			var hours, minutes, seconds;
			seconds = time_left % 60;
			minutes = Math.floor(time_left / 60) % 60;
			hours = Math.floor(time_left / 3600);
	 
			seconds = add_leading_zero( seconds );
			minutes = add_leading_zero( minutes );
			hours = add_leading_zero( hours );
	 
			return hours + ':' + minutes + ':' + seconds;
		}
	 
		function show_time_left() {
			document.getElementById(output_element_id).innerHTML = format_output();//time_left;
		}
	 
		function no_time_left() {
			document.getElementById(output_element_id).innerHTML = no_time_left_message;
		}
	 
		return {
			count: function () {
				countdown();
				show_time_left();
			},
			timer: function () {
				javascript_countdown.count();
	 
				if(keep_counting) {
					setTimeout("javascript_countdown.timer();", 1000);
				} else {
					no_time_left();
				}
			},
			//Kristian Messer requested recalculation of time that is left
			setTimeLeft: function (t) {
				time_left = t;
				if(keep_counting == 0) {
					javascript_countdown.timer();
				}
			},
			init: function (t, element_id) {
				time_left = t;
				output_element_id = element_id;
				javascript_countdown.timer();
			}
		};
	}();
	
	//var stuff = everyone.now.update(format_output());
//setInterval( stuff ,1000);
//Update the countdown clock
//var id1 = setTimeout(never_call,1000);
//var id2 = setInterval(never_call,1000);
//clearTimeout(id1);
//clearInterval(id2);


//////////////////////////////////////////////
//Global stock variables
var OK = false;
var time = 3600;
var userCredit = 1000;
var stockList = [];
var obj1 = { fullName: "Microsoft Corporation", name: "MSFT", price: 4, raised: true };
var obj2 = { fullName: "Apple Inc.", name: "AAPL", price: 4, raised: true };
var obj3 = { fullName: "Bank Of America Corporation", name: "BAC", price: 4, raised: true };
var obj4 = { fullName: "Cisco systems, Inc.", name: "CICO", price: 4, raised: true };
var obj5 = { fullName: "eBay", name: "EBAY", price: 4, raised: true };
var obj6 = { fullName: "Intel Corporation", name: "INTC", price: 4, raised: true };
var obj7 = { fullName: "Targer Corporation", name: "TGT", price: 4, raised: true };
var obj8 = { fullName: "H.J. Heinz Company", name: "HNZ", price: 4, raised: true };
var obj9 = { fullName: "PepsiCo Inc.", name: "PEP", price: 4, raised: true };
stockList.push(obj1);
stockList.push(obj2);
stockList.push(obj3);
stockList.push(obj4);
stockList.push(obj5);
stockList.push(obj6);
stockList.push(obj7);
stockList.push(obj8);
stockList.push(obj9);

function addUser(username, clientID){
	var result;
	var userStocks = [];
	var user = { name: username, balance: 1000, stocks: userStocks};
	result = user;
	console.log("Adding user with name. " + username);
	return result;
}

function getUserStockByName(user, stockname){
	console.log("Getting stocks for user: " + user.name + ".")
	for(var k = 0; k < user.stocks.length; k++){
		if(stockname == user.stocks[k].name){
			return user.stocks[k];
		}
	}	
}
function updateUserStocks(user, stockName, units){
	var userStock = getUserStockByName(user, stockName);
	var stockPrice = getStock(stockName);
	stockPrice.raised = true;
	if(userStock == null){
		console.log("User has not bought this stock before!");
		var newStock = { name: stockName, units: units, price : stockPrice.price};
		user.balance = user.balance - (stockPrice.price * units);
		console.log("New balance is: " + user.balance);
		user.stocks.push(newStock);
	}
	else {
		userStock.units += units;
		user.balance = user.balance - (stockPrice.price * units);
		console.log("New balance is: " + user.balance);
	}
}

function sellUserStocks(user, stockName, units){
	var userStock = getUserStockByName(user, stockName);
	var stockPrice = getStock(stockName);
	stockPrice.raised = false;
	userStock.price = stockPrice.price;
	userStock.units = userStock.units - units;
	user.balance = user.balance + (stockPrice.price * units)
	if(userStock.units <= 0){
		console.log("Stock " + stockName + " for " + user.name + " is <= 0, removing it");
		for(var i = 0;  i < user.stocks.length; i++){
			if (user.stocks[i].name == stockName){
				user.stocks.splice(i, 1);
				break;
			}
		}
	}
}

function getStock(stockName){
	var result = null;
	for(var l = 0; l < stockList.length; l++){
		if(stockName == stockList[l].name){
			result = stockList[l];
		}
	}	
	return result;
}
function updateStockPrices(stockName, units, buying){
	console.log("Updating the stock price for: " + stockName);
	var item = getStock(stockName);
	if(item != null){
		if(buying){
			item.price = item.price + 2;
		}
		else{
			item.price = item.price - 2;
		}
	}
	else{
		console.log("Could not find stock: " + stockName);
	}
}

function updateMyStockValue(user, stockName){
	var stock = getStock(stockName)
	for(var l = 0; l < user.stocks.length; l++){
		if(user.stocks[l].name == stock.name){
			user.stocks[l].price = stock.price;
			return true;
		}
	}
	return false;
}

//server creation and file redering
var fs = require('fs');
//var sys = require('sys');

var static = require('../../node_modules/node-static/lib/node-static');

var file = new(static.Server)('.', { cache: 7200, headers: {'X-Hello':'World!'} });

var server = require('http').createServer(function(request, response){
	//recursive();
	request.addListener('end', function () {
		//
		// Serve files!
		//
		file.serve(request, response, function (err, res) {
			if (err) { // An error as occured
				//sys.error("> Error serving " + request.url + " - " + err.message);
				console.log("> Error serving " + request.url + " - " + err.message);
				response.writeHead(err.status, err.headers);
				response.end();
			} else { // The file was served successfully
				//sys.puts("> " + request.url + " - " + res.message);
				console.log("> " + request.url + " - " + res.message);
			}
		});
	});  
});
server.listen(8080);

function removeOnlineUser(username){
	for(var i = 0;  i < onlineUsers.length; i++){
		if (onlineUsers[i].name == username){
			onlineUsers.splice(i, 1);
			break;
		}
	}
}

var nowjs = require("now");
var everyone = nowjs.initialize(server);
var onlineUsers = [];

nowjs.on('connect', function(){
	OK = true;
	this.now.room = "Main";

	//add user information to user object
	var tempUser = addUser(this.now.name, this.user.clientId);
	this.user.name = tempUser.name;
	this.user.balance = tempUser.balance;
	this.user.stocks = tempUser.stocks;  
	
	nowjs.getGroup(this.now.room).addUser(this.user.clientId);
	onlineUsers.push({ name: this.now.name, id: this.user.clientId} );
	
	//update information on client
	everyone.now.initializeStockInfo(stockList, this.user, onlineUsers);
	console.log("Joined: " + this.user.name + ". balance: " + this.user.balance);
});


nowjs.on('disconnect', function(){
	removeOnlineUser(this.now.name);
	everyone.now.updateOnlineUser(onlineUsers);
	console.log("Left: " + this.now.name);
});

everyone.now.addUserToChat = function(clientId, name){

	nowjs.getGroup(this.now.room).removeUser(this.user.clientId);
	nowjs.getGroup(this.now.room).removeUser(clientId);
	
	this.now.room = this.user.name + " + " + name;
	nowjs.getGroup(this.now.room).addUser(this.user.clientId);
	nowjs.getGroup(this.now.room).addUser(clientId);

	this.now.addChatRoom(this.now.room);
	this.now.receiveMessage("SERVER", "You're now in " + this.now.room);	
} 

everyone.now.buyStock = function(stockName, units){
	console.log("User wants to buy stock " + stockName + ", amount: " + units);
	//Update stock prices
	updateStockPrices(stockName, units, true);	
	//Update user object
	updateUserStocks(this.user, stockName, units);
	//updateAllUserPrices(users, stockName);
	this.now.updateUserStockInfo(this.user);
	everyone.now.updateStockInfo(stockList);
	everyone.now.updateMyStockPrices(stockName);
	//everyone.now.initializeStockInfo(stockList, this.user);
	//everyone.now.updateStockStatus(stockList);
}

everyone.now.sellStock = function(stockName, units){
	console.log("User wants to sell stock " + stockName + ", amount: " + units);
	//Update stock prices
	updateStockPrices(stockName, units, false);	
	//Update user object
	sellUserStocks(this.user, stockName, units);
	
	this.now.updateUserStockInfo(this.user);
	everyone.now.updateStockInfo(stockList);
	everyone.now.updateMyStockPrices(stockName);	
}

everyone.now.updateMyStock = function(stockName){
	console.log("Updating " + this.user.name + " stock price for " + stockName);
	var hasStock = updateMyStockValue(this.user, stockName);
	if(hasStock){
		this.now.updateUserStockInfo(this.user);
	}
}

everyone.now.changeRoom = function(newRoom){
  nowjs.getGroup(this.now.room).removeUser(this.user.clientId);
  nowjs.getGroup(newRoom).addUser(this.user.clientId);
  this.now.room = newRoom;
  this.now.receiveMessage("SERVER", "You're now in " + this.now.room);
}

everyone.now.distributeMessage = function(message){
  nowjs.getGroup(this.now.room).now.receiveMessage(this.now.name, message);
};

//Counter implementation
everyone.now.update = function(){
  everyone.now.countDownTime(format_output());
};

var recursive = function () {
    //console.log("It has been one second! " + "counter: " + time);
	if(OK){
		everyone.now.update();
	}
	time = time - 1;
	if(time == 0){
		console.log("TIME IS UP!!!");
	}	
	else{
		setTimeout(recursive,1000);	
	}
     
}
recursive();

function add_leading_zero(n) {
	if(n.toString().length < 2) {
		return '0' + n;
	} else {
		return n;
	}
}

function format_output() {
	var hours, minutes, seconds;
	seconds = time % 60;
	minutes = Math.floor(time / 60) % 60;
	hours = Math.floor(time / 3600);

	seconds = add_leading_zero( seconds );
	minutes = add_leading_zero( minutes );
	hours = add_leading_zero( hours );

	return hours + ':' + minutes + ':' + seconds;
}






